<?php
namespace lib;

class Request{

    protected $ch;
    protected $cookie;
    protected $userAgent;
    protected $cookiePath;

    function __construct(){
        $this->cookiePath = ROOT_PATH . DS . 'cookie';
        is_dir($this->cookiePath) || mkdir($this->cookiePath, 0777, true);
        $this->userAgent = $_SERVER['HTTP_USER_AGENT'];
    }

    function url($url){
        $this->ch = curl_init();
        curl_setopt($this->ch, CURLOPT_URL, $url);
        return $this;
    }

    function attache($params){
	    $data = [];
    	$file = new \CURLFile($params['path'], $params['mime'], $params['name']);
    	$data[$params['field_name']] = $file;
	    curl_setopt($this->ch, CURLOPT_POSTFIELDS, $data);
	    return $this;
    }

    function setData($data){
        curl_setopt($this->ch, CURLOPT_POSTFIELDS, http_build_query($data));
        return $this;
    }

    function setHeader($headers){
        curl_setopt($this->ch, CURLOPT_HTTPHEADER, $headers);
        return $this;
    }

    function setReferer($referer){
        curl_setopt($this->ch, CURLOPT_REFERER, $referer);
        return $this;
    }

    function setUserAgent($userAgent){
        $this->userAgent = $userAgent;
        return $this;
    }

    function autoCookie(){
        $fileList = scandir($this->cookiePath);
        if(isset($fileList['2'])){
            $this->cookie = ROOT_PATH . DS . 'cookie' . DS . $fileList['2'];
        }else{
            $this->cookie = tempnam(ROOT_PATH . DS . 'cookie', 'cookie');
        }
        return $this;
    }

    function setCookie($filename){
        $this->cookie = $filename;
        return $this;
    }

    function cookie($prefix = 'cookie'){
        $cookie = tempnam($this->cookiePath, $prefix);
        return $cookie;
    }

    function setFollow(){
        curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION,true);      //跟踪301
        return $this;
    }

    function setReuse(){
        curl_setopt($this->ch, CURLOPT_FRESH_CONNECT,false);
        curl_setopt($this->ch, CURLOPT_FORBID_REUSE,false);
        curl_setopt($this->ch, CURLOPT_TIMEOUT,60);
        return $this;
    }

    function setMethod($method){
        curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
        return $this;
    }

    function debug(){
        error_reporting(E_ALL);
        curl_setopt($this->ch, CURLOPT_HEADER, true);
        return $this;
    }

    function send(){
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($this->ch, CURLOPT_USERAGENT, $this->userAgent);   //用户访问代理 User-Agent
        curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER,0);      //不验证证书
        if($this->cookie){
            curl_setopt($this->ch, CURLOPT_COOKIEFILE, $this->cookie);
            curl_setopt($this->ch, CURLOPT_COOKIEJAR, $this->cookie);
        }
        $result = curl_exec($this->ch);
        curl_close($this->ch);
        return $result;
    }

}